<template>
  <el-container class="widget-edit-container module-edit-container">
    <el-aside class="aside-left">
      <el-card shadow="never" body-class="aside-card-body">
        <template #header>
          <span>
            <svg-icon icon-class="el-set-up" />
            {{ i18nt('designer.componentLib') }}
          </span>
        </template>
        <el-scrollbar class="components-scrollbar" :style="{ height: scrollerHeight + 'px' }" always>
          <ul @dragover="onComponentDragOver">
            <li v-for="component in widgetList" :key="component.type" :class="{
              'field-widget-item': true,
              'field-widget-item-disabled': !designer || component.disabled
            }" :title="component.displayName" :draggable="designer && !component.disabled ? true : false"
              @dblclick="addFieldByDbClick(component)" @dragstart="onComponentDragStart(component, $event)">
              <span><svg-icon :icon-class="component.icon" class-name="color-svg-icon" />{{
                i18nt(`designer.widgetLabel.${component.type}`)
                }}</span>
            </li>
          </ul>
        </el-scrollbar>
      </el-card>
    </el-aside>

    <!--中间画图-->
    <el-main class="widget-edit-main">
      <el-scrollbar class="widget-designer-scroll" style="height: 488px" always>
        <div class="widget-designer" :style="{ width: canvasWidth + 60 + 'px', height: canvasHeight + 60 + 'px' }">
          <div ref="horizontalRuler" class="ruler horizontal-ruler"></div><!--水平边线 -->
          <div ref="verticalRuler" class="ruler vertical-ruler"></div><!--边线 -->
          <div class="widget-canvas-cantainer">
            <!--下面是整个画布-->
            <div ref="widgetCanvasRef" class="widget-canvas module-edit-canvas" :style="{
              width: canvasWidth + 'px',
              height: canvasHeight + 'px',
              backgroundColor: widget.options.color
            }" @click="canvasClickHandler" @dragover="onDragOver" @drop="onDrop" @contextmenu.stop="onContextMenu" @mousemove="updateMousePosition">
              <component :is="getWidgetName(cWidget)" v-for="(cWidget, index) in pageChildren" :key="cWidget.id"
                :ref="cWidget.id" :field="cWidget" :designer="designer" :settings="settings" :parent-list="pageChildren"
                :index-of-parent-list="index" :parent-widget="widget" :design-state="true" :widget-edit="true" :style="{
                  left: cWidget.options.x + 'px',
                  top: cWidget.options.y + 'px'
                }"></component>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-main>


    <!--右边菜单栏-->
    <el-aside class="aside-right">
      <el-tabs v-model="activeTabName" type="card">
        <el-tab-pane name="default" :label="i18nt('designer.hint.page')">
          <div class="page-toolbar">
            <el-tooltip content="新建页面" placement="top" effect="light">
              <el-button link type="primary" icon="el-icon-document-add" @click="addPage"></el-button>
            </el-tooltip>
            <el-tooltip content="删除页面" placement="top" effect="light">
              <el-button link type="primary" icon="el-icon-document-remove" @click="deletePage"></el-button>
            </el-tooltip>
            <el-tooltip content="上移页面" placement="top" effect="light">
              <el-button link type="primary" icon="el-icon-top" @click="moveUpPage"></el-button>
            </el-tooltip>
            <el-tooltip content="下移页面" placement="top" effect="light">
              <el-button link type="primary" icon="el-icon-bottom" @click="moveDownPage"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="复制组件 (Ctrl+C)" placement="top" effect="light">
  <el-button link type="primary" icon="el-icon-document-copy" @click="copySelectedWidget"></el-button>
</el-tooltip>
<el-tooltip content="粘贴组件 (Ctrl+V)" placement="top" effect="light">
  <el-button link type="primary" icon="el-icon-document-add" @click="pasteWidget"></el-button>
</el-tooltip> -->
          </div>

          <!--放置列表-->
          <el-scrollbar class="setting-scrollbar" :style="{ height: pageScrollBarHeight + 'px' }" always>
            <template v-for="(widget2, ind2) in pageList" :key="widget2.id">
              <div @click="selectPageNode(ind2)" class="baseNodeCls" :class="{ selectNodeCls: ind2 == pageIndex }">
                <div>
                  {{ '第' +(ind2+1)+ '页 ('+widget2.name +')'}}
                </div>
              </div>
            </template>
          </el-scrollbar>

        </el-tab-pane>
      </el-tabs>

      <el-tabs type="card" :style="{ height: '200px' }">
        <el-tab-pane :label="i18nt('designer.hint.widgetSetting')">
          <el-scrollbar class="property-setting-scrollbar" :style="{ height: scrollerHeight + 'px' }" always>
            <template v-if="selectedWidget">
              <el-form :model="optionModel" size="small" label-position="right" label-width="90px" class="setting-form"
                @submit.prevent>
                <el-collapse v-model="collapseNames" class="setting-collapse">
                  <el-collapse-item v-if="appearancePropList.length > 0" name="1" title="外观">
                    <template v-for="editorName in appearancePropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)"></component>
                    </template>
                  </el-collapse-item>

                  <el-collapse-item v-if="positionSizePropList.length > 0" name="2" title="位置尺寸">
                    <template v-for="editorName in positionSizePropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)" :parent-widget="widget">
                      </component>
                    </template>
                  </el-collapse-item>

                  <el-collapse-item v-if="miscPropList.length > 0" name="3" title="杂项">
                    <template v-for="editorName in miscPropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)"></component>
                    </template>
                  </el-collapse-item>

                  <el-collapse-item v-if="fontPropList.length > 0" name="4" title="字体">
                    <template v-for="editorName in fontPropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)"></component>
                    </template>
                  </el-collapse-item>

                  <el-collapse-item v-if="dataPropList.length > 0" name="3" title="数据">
                    <template v-for="editorName in dataPropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)"></component>
                    </template>
                  </el-collapse-item>

                  <el-collapse-item v-if="eventPropList.length > 0" name="6" title="事件">
                    <template v-for="editorName in eventPropList" :key="editorName">
                      <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                        :option-model="optionModel" :disabled="widgetPropDisabled(editorName)"></component>
                    </template>
                  </el-collapse-item>
                </el-collapse>
              </el-form>
            </template>
          </el-scrollbar>
        </el-tab-pane>

        <el-tab-pane label="页内组件" style="padding: 10px 0;overflow-y: auto;" :style="{ height: scrollerHeight + 'px' }">
          <template v-for="(widget2, ind2) in pageWidgetList" :key="widget2.id">
            <div @click="selectNode(ind2)" class="baseNodeCls" :class="{ selectNodeCls: ind2 == seleNodeInd }">
              <div>
                {{ widget2.name }}
              </div>
              <div @click="delNode(ind2)">
                删除
              </div>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-aside>

    <el-dialog v-model="showWidgetEventDialogFlag"
      :title="`${i18nt(`designer.widgetLabel.${selectedWidget && selectedWidget.type}`)}组件${curEventName}编辑`"
      :show-close="true" class="code-editor-dialog small-padding-dialog" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" :destroy-on-close="true" draggable>
      <div class="variable-info" v-if="selectedWidget">
    <p>控件ID : {{selectedWidget.options.name}}</p>
    <p >当前函数的通用变量(以下变量只在当前控件的范围有效)</p>
<p>objId : 指的是当前控件的ID（{{ selectedWidget.options.name }}），可以通过函数get_obj_width、get_obj_height、set_obj_width、set_obj_attr_ext1等函数获取和设置控件信息</p>
      <p>value : 当前控件的值</p>
  </div>
      <code-editor ref="ecEditor" v-model="eventHandlerCode" :mode="'lua'" :readonly="false"></code-editor>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showWidgetEventDialogFlag = false">
            {{ i18nt('designer.hint.cancel') }}</el-button>
            <el-button type="success" @click="handleWidgetPreview">
        {{ i18nt('designer.hint.simulate') }}</el-button>
          <el-button type="primary" @click="saveEventHandler">
            {{ i18nt('designer.hint.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import * as ELECTRON from '@/electron'
import Ruler from '@scena/ruler'
import { widgetList as BFS, slideWidgetList } from '@/designer/widget-panel/widgetsConfig'
import {
  APPEARANCE_PROPERTIES,
  POSITION_SIZE_PROPERTIES,
  FONT_PROPERTIES,
  DATA_PROPERTIES,
  MISC_PROPERTIES,
  EVENT_PROPERTIES
} from '@/designer/setting-panel/propertyRegister'
import * as CONST from '@/designer/const'
import { useMouseInElement } from '@vueuse/core'
import { ref } from 'vue'
import { translate } from '@/i18n'
import emitter from '@/mixins/emitter'

export default {
  name: 'SlideWidget',
  componentName: 'SlideWidget',
  mixins: [emitter],
  provide() {
    return {
      refList: this.widgetRefList,
      getOptionData: () => this.optionData,
      globalModel: {
        formModel: this.formModel
      }
    }
  },
  props: {
    designer: Object,
    settings: Object,
    widget: Object
  },
  setup() {
    const widgetCanvasRef = ref(null)
    const { elementX, elementY, elementWidth, elementHeight } = useMouseInElement(widgetCanvasRef)
    return {
      widgetCanvasRef,
      elementX,
      elementY,
      elementWidth,
      elementHeight
    }
  },
  data() {
    return {
      // 允许作为子组件的组件列表
      widgetList: BFS.filter((widget) => slideWidgetList.includes(widget.type)).map((config) => {
        // console.log(config)
        return {
          ...config,
          displayName: translate(`designer.widgetLabel.${config.type}`)
        }
      }),

      // 滚动条高度
      scrollerHeight: 400,
      pageScrollBarHeight: 130,

      collapseNames: ['1', '2', '3', '4', '5', '6'],
      formModel: {},
      widgetRefList: {},
      vRuler: null,
      hRuler: null,

      activeTabName: 'default',

      seleNodeInd: -1,

      showWidgetEventDialogFlag: false,
      eventHandlerCode: '',
      curEventName: '',
      pageIndex: 0,
      pageNo: 10000,
      mousePosition: { x: 0, y: 0 },
    }
  },
  computed: {

    pageList() {
      let li = []
      let widgetL = this.widgetChildren
      Object.keys(widgetL).forEach(function(key) {
        li.push({name: widgetL[key].options.name, checked: false})
      })
      return li
    },

    pageWidgetList() {
      let li = []
      let widgetL = this.pageChildren
      Object.keys(widgetL).forEach(function (key) {
        li.push({ name: widgetL[key].options.name, checked: false })
      })
      return li
    },

    optionModel() {
      return this.selectedWidget && this.selectedWidget.options
    },

    currentWidget() {
       return this.widgetChildren[this.pageIndex]
    },

    pageChildren() {
      let ret = this.widgetChildren;

      if (ret.length == 0) {
        let page =this.pageInit();
        ret.push(page)
      }
      return ret[this.pageIndex]["widgetList"]
    },

    widgetChildren() {
      let widgetLi = this.widget.widgetList || []
      return widgetLi
    },
    selectedWidget() {
      return this.designer ? this.designer.selectedWidget : null
    },
    backgroundPositionX() {
      const align = this.widget.options.pngAlign
      if (
        align === CONST.ALIGN_TYPE.LV_ALIGN_TOP_LEFT ||
        align === CONST.ALIGN_TYPE.LV_ALIGN_LEFT_MID ||
        align === CONST.ALIGN_TYPE.LV_ALIGN_BOTTOM_LEFT
      ) {
        return 'left'
      } else if (
        align === CONST.ALIGN_TYPE.LV_ALIGN_TOP_RIGHT ||
        align === CONST.ALIGN_TYPE.LV_ALIGN_RIGHT_MID ||
        align === CONST.ALIGN_TYPE.LV_ALIGN_BOTTOM_RIGHT
      ) {
        return 'right'
      } else {
        return 'center'
      }
    },

    appearancePropList() {
      // console.log('2=====> ')
      // console.log(APPEARANCE_PROPERTIES)

      if (!this.optionModel) {
        return []
      }
      return Object.keys(APPEARANCE_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return APPEARANCE_PROPERTIES[prop]
        })
    },
    positionSizePropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(POSITION_SIZE_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return POSITION_SIZE_PROPERTIES[prop]
        })
    },
    fontPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(FONT_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return FONT_PROPERTIES[prop]
        })
    },
    dataPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(DATA_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return DATA_PROPERTIES[prop]
        })
    },
    miscPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(MISC_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return MISC_PROPERTIES[prop]
        })
    },
    eventPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(EVENT_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return EVENT_PROPERTIES[prop]
        })
    },

    //画布宽度
    canvasWidth() {
      return this.widget.options.width - (this.widget.options.slideButtonWidth * 2)
    },

    canvasHeight() {
      return this.widget.options.height
    }
  },
  watch: {
    canvasHeight(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$nextTick(() => {
          this.reRenderVerticalRuler(newVal)
        })
      }
    },

    selectedWidget(newVal) {
      if (newVal == null) {
        return
      }
      let widgetL = this.widgetChildren
      // console.log(newVal)
      for (let ind in widgetL) {
        if (widgetL[ind].options.name == newVal.options.name) {
          this.seleNodeInd = ind
        }
      }
    },
    canvasWidth(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$nextTick(() => {
          this.reRenderHorizontalRuler(newVal)
        })
      }
    }
  },
  mounted() {
    this.on$('editEventHandler', (eventParams) => {
      this.$emitter.on('slide-copy', this.handleSlideCopy)
      this.editEventHandler(eventParams[0], eventParams[1])
    })
    this.$emitter.on('widget-drag-end', this.handleDragEnd)

    // this.$emitter.off('pasteWidget')
    // this.$emitter.on('pasteWidget', this.pasteWidget)

    this.widgetCanvasRef = this.$refs.widgetCanvasRef

    this.reRenderHorizontalRuler(this.canvasWidth)
    this.reRenderVerticalRuler(this.canvasHeight)
    document.addEventListener('keydown', this.handleKeyDown)
  },

  unmounted() {
    this.$emitter.off('slide-copy', this.handleSlideCopy)
    this.$emitter.off('widget-drag-end', this.handleDragEnd)
    document.removeEventListener('keydown', this.handleKeyDown)
  },
  methods: {
    // 处理键盘事件
   handleKeyDown(event) {
    // 检查是否在代码编辑区（如textarea或contenteditable元素）
    const activeElement = document.activeElement;
    const isInCodeEditor = activeElement.tagName === 'TEXTAREA' ||
      activeElement.tagName === 'INPUT' ||
      activeElement.isContentEditable;

    if (isInCodeEditor) {
      return; // 如果在代码编辑区，不处理快捷键
    }
    // 检查是否按下了 Ctrl 键
    if (event.ctrlKey || event.metaKey) {
      switch (event.key.toLowerCase()) {
        case 'c':
          // 阻止默认行为
          event.preventDefault()
          this.copySelectedWidget()
          break
        case 'v':
          // 阻止默认行为
          event.preventDefault()
          // 直接调用粘贴方法，不再通过事件发射器
          this.pasteWidget(this.mousePosition)
          break
      }
    }
  },
    addPage() {
      let ret = this.widgetChildren;
      let page = this.pageInit();
      ret.push(page)
    },
    deletePage() {
      let ret = this.widgetChildren;
      if(ret.length < 2) {
        this.$message.warning('至少保留一个页面')
        return
      }

      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ret.splice(this.pageIndex, 1)
        this.pageIndex--
      })
    },
    moveUpPage() {

    },
    moveDownPage() {

    },

    pageInit() {
      let lastId = this.designer.getLastId();
      let page = {
        "type": "module",
        "icon": "module-filed",
        "widgetList": [],
        "options": {
          "parentId": 0,
          "id": lastId,
          "name": 'slidepage'+lastId,
          "width": this.canvasWidth,
          "height": this.canvasHeight,
          "color": "#FFFFFF",
          "colorLine": "#808080",
          "widthLine": 0,
          "opa": 255,
          "radius": 0,
          "scrollWidth": 0,
          "scrollHeight": 0,
          "hidden": 0,
          "baseId": 0,
          "align": 1,
          "x": 0,
          "y": 0
        },
        "id": lastId
      }
      return page;
    },

    //选中
    // selectNode(index) {
    //   // console.log(index)
    //   // console.log(this.designer)

    //   // eslint-disable-next-line vue/no-mutating-props
    //   this.designer.selectedWidget = this.widgetChildren[index]
    // },
    // 修改选中方法
  selectNode(index) {
    this.seleNodeInd = index
    this.designer.selectedWidget = this.pageChildren[index]
  },

    selectPageNode(index) {
      this.pageIndex = index
    },

    // delNode(index) {
    //   this.$confirm('是否继续删除?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.widgetChildren.splice(index, 1)
    //   })
    // },
    delNode(index) {
    this.$confirm('是否继续删除?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 确保删除的是当前页面的组件
      this.pageChildren.splice(index, 1)
      this.designer.emitHistoryChange()  // 记录历史变更
    })
  },
    // In index.vue methods section, add these new methods:

handleSlideCopy() {
  if (!this.designer.selectedWidget) return
  
  // For slide components, we need to handle copy differently
  let newWidget = deepClone(this.designer.selectedWidget)
  let tempId = generateId()
  newWidget.id = newWidget.type.replace(/-/g, '') + tempId

  let lastId = this.designer.getLastId()
  newWidget.options.id = lastId
  newWidget.options.name = `${newWidget.type}${lastId}`

  if (newWidget.options.userId) {
    newWidget.options.userId = this.designer.getLastUserId()
  }

  if (newWidget.widgetList) {
    this.copyWidgetListForSlide(newWidget.widgetList)
  }

  this.designer.copyWidget = newWidget
},

copyWidgetListForSlide(copyWidgetList) {
  copyWidgetList.forEach((widget) => {
    widget.id = widget.type.replace(/-/g, '') + generateId()

    let lastId = this.designer.getLastId()
    widget.options.id = lastId
    widget.options.name = `${widget.type}${lastId}`

    if (widget.options.userId) {
      widget.options.userId = this.designer.getLastUserId()
    }

    if (widget.widgetList) {
      this.copyWidgetListForSlide(widget.widgetList)
    }
  })
},

handleSlidePaste(position, scale = 1) {
  if (!this.designer.copyWidget) return

  if (!position) {
    this.designer.copyWidget.options.x += 50
    this.designer.copyWidget.options.y += 50
  } else {
    this.designer.copyWidget.options.x = Math.round(position.x / scale)
    this.designer.copyWidget.options.y = Math.round(position.y / scale)
  }

  // Add to current page's widget list
  this.pageChildren.push(this.designer.copyWidget)
  
  // Make a new copy for next paste
  this.handleSlideCopy()
  
  this.designer.emitHistoryChange()
},
    // 复制组件
    copySelectedWidget() {
      const copyWidget = this.designer.selectedWidget
      if (!copyWidget) return

      if (copyWidget.type === 'module') {
        let newWidget = deepClone(copyWidget)
        let tempId = generateId()
        newWidget.id = newWidget.type.replace(/-/g, '') + tempId

        let lastId = this.designer.getLastId()
        newWidget.options.id = lastId
        newWidget.options.name = `${newWidget.type}${lastId}`

        if (newWidget.options.userId) {
          newWidget.options.userId = this.designer.getLastUserId()
        }

        if (newWidget.widgetList) {
          this.copyWidgetList(newWidget.widgetList)
        }

        this.designer.copyWidget = newWidget
      } else {
        this.designer.copySelectedWidget(copyWidget)
      }
    },

    // 粘贴组件
    pasteWidget(position = null, targetList = null, scale = 1) {
  if (!this.designer.copyWidget) return

  // 如果没有传入位置参数，使用存储的鼠标位置
  const pastePosition = position || this.mousePosition

  const widgetListToUse = targetList || this.pageChildren

  // 如果没有指定位置，默认偏移50像素
  if (!position) {
    this.designer.copyWidget.options.x += 50
    this.designer.copyWidget.options.y += 50
  } else {
    this.designer.copyWidget.options.x = Math.round(pastePosition.x / scale)
    this.designer.copyWidget.options.y = Math.round(pastePosition.y / scale)
  }

  widgetListToUse.push(this.designer.copyWidget)
  this.copySelectedWidget()
  this.designer.emitHistoryChange()
},
updateMousePosition(event) {
  const canvasRect = this.$refs.widgetCanvasRef.getBoundingClientRect()
  this.mousePosition = {
    x: event.clientX - canvasRect.left,
    y: event.clientY - canvasRect.top
  }
},

    widgetPropDisabled(editorName) {
      if (editorName === 'scrollHeight-editor' || editorName === 'scrollWidth-editor') {
        return false
      }

      if (this.selectedWidget.id === this.widget.id) {
        return true
      }

      return false
    },

    canvasClickHandler() {
      console.log('canvasClickHandler---');
      this.designer.setSelected(this.widget)
    },


    // 添加上下文菜单项
    onContextMenu(event) {
  console.log('onContextMenu---')
  event.preventDefault()
  this.designer.setSelected(null)

  // For slide components, use special copy handler
  if (this.selectedWidget && this.selectedWidget.type === 'module') {
    this.$emitter.emit('showContextMenu', {
      clientX: event.clientX,
      clientY: event.clientY,
      designerId: this.designer.id,
      isSlide: true
    })
  } else {
    this.$emitter.emit('showContextMenu', {
      clientX: event.clientX,
      clientY: event.clientY,
      designerId: this.designer.id
    })
  }
},


    onDragOver(evt) {
      console.log('onDragOver---');
      evt.preventDefault()

      const widget = this.designer.dragWidget
      if (this.$refs[widget.id] && this.$refs[widget.id].length > 0) {
        const translateX = this.elementX - widget.options.x - widget.offset.x
        const translateY = this.elementY - widget.options.y - widget.offset.y

        const widgetInstance = this.$refs[widget.id][0]
        widgetInstance.$el.style.transform = `translate(${translateX}px, ${translateY}px)`
      }
    },

    //落地
    onDrop(evt) {
      console.log('onDrop---')
      evt.preventDefault()
      // console.log('打印designer:', this.designer)
      // console.log('打印settings:', this.settings)
      // console.log('打印widget:', this.widget)

      if (evt.dataTransfer.effectAllowed === 'copy') {

        const widget = this.designer.dragWidget
        this.designer.addDragWidget(widget, this.currentWidget)

        this.updateWidgetPosition(widget)
        // 清除拖拽元素
        this.designer.drag(null)

        // 保存操作历史
        this.designer.emitHistoryChange()
      }
    },

    handleDragEnd(widget) {
      console.log('handleDragEnd---')
      if (this.designer.hasWidget(widget, this.pageChildren)) {
        this.updateWidgetPosition(widget)

        if (this.$refs[widget.id] && this.$refs[widget.id].length > 0) {
          const widgetInstance = this.$refs[widget.id][0]
          widgetInstance.$el.style.transform = `translate(0, 0)`
        }

        // 清除拖拽元素
        this.designer.drag(null)
        // 保存操作历史
        this.designer.emitHistoryChange()
      }
    },

    handleFieldWidgetClone(origin) {
      console.log('handleFieldWidgetClone---')
      return this.designer.copyNewFieldWidget(origin, this.widget)
    },

    onComponentDragStart(widget, evt) {
      console.log('onComponentDragStart---')
      const widgetCopy = this.designer.copyNewFieldWidget(widget)
      widgetCopy.offset = {
        x: evt.offsetX,
        y: evt.offsetY
      }
      this.designer.drag(widgetCopy)
      evt.dataTransfer.effectAllowed = 'copy'
    },

    onComponentDragOver(evt) {
      console.log('onComponentDragOver---')
      evt.preventDefault()
    },
    addFieldByDbClick(widget) {
      console.log('addFieldByDbClick---')
      this.designer.addFieldByDbClick(widget, this.widget)
    },

    reRenderHorizontalRuler(width) {
      console.log('reRenderHorizontalRuler---')
      if (this.hRuler) {
        this.$refs.horizontalRuler.removeChild(this.$refs.horizontalRuler.querySelector('canvas'))
        this.hRuler = null
      }

      this.hRuler = new Ruler(this.$refs.horizontalRuler, {
        type: 'horizontal',
        width: width + 30,
        height: 30,
        backgroundColor: '#daeaff',
        lineColor: '#000000',
        textColor: '#154a93',
        textAlign: 'right'
      })
    },
    reRenderVerticalRuler(height) {
      console.log('reRenderVerticalRuler---')
      if (this.vRuler) {
        this.$refs.verticalRuler.removeChild(this.$refs.verticalRuler.querySelector('canvas'))
        this.vRuler = null
      }
      this.vRuler = new Ruler(this.$refs.verticalRuler, {
        type: 'vertical',
        width: 30,
        height: height + 30,
        backgroundColor: '#daeaff',
        lineColor: '#000000',
        textColor: '#154a93'
      })
    },
    getWidgetName(widget) {
      return widget.type + '-widget'
    },

    updateWidgetPosition(widget) {
      console.log('updateWidgetPosition---')
      if (widget) {
        this.designer.setSelected(widget)
        this.$nextTick(() => {
          if (widget.offset) {
            widget.options.x = this.elementX - widget.offset.x
            widget.options.y = this.elementY - widget.offset.y
            const { width = 100, height = 100 } = widget.options

            if (widget.options.x < 0) {
              widget.options.x = 0
            } else if (widget.options.x + width > this.elementWidth) {
              widget.options.x = this.elementWidth - width
            }

            if (widget.options.y < 0) {
              widget.options.y = 0
            } else if (widget.options.y + height > this.elementHeight) {
              widget.options.y = this.elementHeight - height
            }

            widget.options.x = Math.round(widget.options.x)
            widget.options.y = Math.round(widget.options.y)
            delete widget.offset
          }
        })
      }
    },

    getWidgetRef(widgetName, showError = false) {
      let foundRef = this.widgetRefList[widgetName]
      if (!foundRef && !!showError) {
        this.$message.error(this.i18nt('designer.hint.refNotFound') + widgetName)
      }
      return foundRef
    },

    clearWidgetRefList() {
      console.log('clearWidgetRefList---')
      Object.keys(this.widgetRefList).forEach((widgetRef) => {
        delete this.widgetRefList[widgetRef]
      })
    },

    deleteWidgetRef(widgetRefName) {
      console.log('deleteWidgetRef---')
      delete this.widgetRefList[widgetRefName]
    },

    editEventHandler(eventName) {
      this.curEventName = eventName
      this.eventHandlerCode = this.selectedWidget.options[eventName] || ''

      this.showWidgetEventDialogFlag = true
    },
    handleWidgetPreview() {
  // 先保存代码但不关闭对话框
  this.saveEventHandler(false).then((success) => {
    if (success) {
      // 触发页面仿真
      this.$emitter.emit('CLEAR_DEBUG_LOG')
      this.$emitter.emit(
        'START_PAGE_DEBUG',
        (this.designer && this.designer.options.name) || ''
      )
    }
  })
},

saveEventHandler(closeDialog = true) {
  return new Promise((resolve) => {
    const codeHints = this.$refs.ecEditor.getEditorAnnotations()
    let syntaxErrorFlag = false
    if (!!codeHints && codeHints.length > 0) {
      codeHints.forEach((chItem) => {
        if (chItem.type === 'error') {
          syntaxErrorFlag = true
        }
      })

      if (syntaxErrorFlag) {
        this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
        resolve(false)
        return
      }
    }

    this.selectedWidget.options[this.curEventName] = this.eventHandlerCode
    if (closeDialog) {
      this.showWidgetEventDialogFlag = false
    }
    resolve(true)
  })
},

    // saveEventHandler() {
    //   console.log('saveEventHandler---')
    //   const codeHints = this.$refs.ecEditor.getEditorAnnotations()
    //   let syntaxErrorFlag = false
    //   if (!!codeHints && codeHints.length > 0) {
    //     codeHints.forEach((chItem) => {
    //       if (chItem.type === 'error') {
    //         syntaxErrorFlag = true
    //       }
    //     })

    //     if (syntaxErrorFlag) {
    //       this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
    //       return
    //     }
    //   }

    //   this.selectedWidget.options[this.curEventName] = this.eventHandlerCode
    //   this.showWidgetEventDialogFlag = false
    // }
    
  }
}
</script>

<style lang="scss" scoped>
.variable-info {
  padding: 5px 12px;
  margin-bottom: 5px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  font-size: 12px;
  color: #606266;
}
.selectNodeCls {
  background: #f0d292;
}

.baseNodeCls {
  padding: 6px 15px;
  box-sizing: border-box;
  font-size: 12px;
  display: grid;
  grid-template-columns: 3fr 1fr;

  &:hover {
    cursor: pointer;
  }
}

.widget-edit-container {
  position: relative;

  :deep(.el-card) {
    margin-top: 0;

    .el-card__header {
      background-color: #daeaff;
      color: #083772;
      font-size: 12px;
      padding: 10px 15px;
    }

    .el-card__body {
      padding: 4px;
      border: #6593cf solid 1px;
    }
  }

  .aside-left {
    width: 180px;

    ul {
      padding-left: 10px;
      /* 重置IE11默认样式 */
      margin: 0;
      /* 重置IE11默认样式 */
      margin-block-start: 0;
      margin-block-end: 0.25em;
      padding-inline-start: 10px;

      &:after {
        content: '';
        display: block;
        clear: both;
      }

      .field-widget-item {
        display: inline-block;
        height: 24px;
        line-height: 24px;
        font-size: 11px;
        width: 98px;
        margin: 2px 6px 6px 0;
        cursor: move;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        background: #fff;
        border: 1px solid #e8e9eb;
        border-radius: 4px;
        padding: 0 8px;

        &:hover {
          background: #ffeaa6;
          border-color: #e49c05;
          color: $--color-primary;

          .color-svg-icon {
            color: $--color-primary;
          }
        }
      }

      .field-widget-item.field-widget-item-disabled {
        color: #808080;
        cursor: not-allowed;

        &:hover {
          background: #e8e9eb;
          border-color: #e8e9eb;

          .color-svg-icon {
            color: #808080;
            fill: #808080;
          }
        }
      }
    }
  }

  .widget-edit-main {
    padding-top: 0;
    padding-bottom: 0;

    .widget-designer-scroll {
      .widget-designer {
        position: relative;
        background: #daeaff;
        overflow: hidden;

        .ruler {
          position: absolute;
          top: 0;
          left: 0;
        }

        .ruler.horizontal-ruler {
          left: 30px;
          right: 0;
        }

        .ruler.vertical-ruler {
          top: 30px;
          bottom: 0;
        }

        .widget-canvas-cantainer {
          position: absolute;
          left: 30px;
          right: 30px;
          top: 30px;
          bottom: 30px;
          background: #ffffff;

          :deep(.el-row) {
            padding: 2px;
            border: 1px dashed rgba(170, 170, 170, 0.75);
          }
        }
      }
    }
  }

  .aside-right {
    width: 300px;

    .setting-form {
      padding: 0 6px;

      :deep(.el-form-item__label) {
        font-size: 11px;
        overflow: hidden;
        white-space: nowrap;
      }

      :deep(.el-form-item--small.el-form-item) {
        margin-bottom: 10px;
      }

      :deep(.el-slider) {
        .el-slider__runway {
          margin-right: 16px;
        }

        .el-slider__input {
          width: 85px !important;
        }
      }

      :deep(.el-select) {
        width: 178px !important;
      }
    }
  }
}
</style>
